package cn.feuler.user8080.service;

import cn.feuler.common.entity.Token;
import cn.feuler.user8080.mapper.TokenMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;

@Service
public class TokenService {

    private final TokenMapper tokenMapper;

    public TokenService(TokenMapper tokenMapper) {
        this.tokenMapper = tokenMapper;
    }

    public String info(String token) {
        Token exists = tokenMapper.selectOne(new QueryWrapper<Token>().eq("token", token));
        if (exists != null) {
            return exists.getEmail();
        }
        return null;
    }

    public Token save(String email) {
        Token token = new Token();
        token.setEmail(email);
        Token exists = tokenMapper.selectOne(new QueryWrapper<>(token));
        if (exists != null) {
            return exists;
        }
        token.setToken(RandomStringUtils.randomAlphanumeric(16));
        tokenMapper.insert(token);
        return token;
    }
}
